<?php

class openapi_api_function_v1_goods extends openapi_api_function_abstract implements openapi_api_function_interface{

    public function getList($params,&$code,&$sub_msg)
    {
        $account_id = $this->checklogin($params['login_token']);
        $store_grade = 0;
        $sub_store_grade = array();
        if($account_id){
            $store = app::get("business")->model('storemanger')->getRow("store_grade",array('account_id'=>$account_id));
            $store_grade = $store['store_grade'];
            $substore = app::get('business')->model('storegrade')->getList('grade_id',array('parent_id'=>$store_grade));
            foreach ($substore as $key => $value) {
                $sub_store_grade[] = $value['grade_id'];
            }
        }
        $params = array_filter($params);
        //筛选条件  1、根据条件筛选出ID
        $where = "1=1 ";
        if(isset($params['cat_id']) && !empty($params['cat_id'])){
            $cats = app::get('b2c')->model('goods_cat')->getList("cat_id",array('cat_path|has'=>','.$params['cat_id'].','));
            $new_cats = array();
            foreach ($cats as $key => $value) {
                $new_cats[] = $value['cat_id'];
            }
            $new_cats[] = $params['cat_id'];
            $where .= "and g.cat_id in ('".implode("','", $new_cats)."') ";
        }
        if(isset($params['filter_list']) && !empty($params['filter_list'])){
            foreach ($params['filter_list'] as $f_k => $f_v) {
                if($f_v['name']=='spec' || $f_v['name']=='rating'){
                    continue;//todo
                }
                if($f_v['type']=='between'){
                    $f_v['content'] = explode(',', $f_v['content']);
                    $where .= "and (".$f_v['name']." between ".$f_v['content'][0]." and ".$f_v['content'][1].") ";
                }elseif ($f_v['type']=='in') {
                    $f_v['content'] = explode(',', $f_v['content']);
                    $where .= " and ".$f_v['name']." in ('".implode("','", $f_v['content'])."') ";
                }
            }
        }
        //搜索条件
        if(isset($params['scontent']) && !empty($params['scontent'])){
            $where .= " and (g.name like '%".$params['scontent']."%' or g.bn like '%".$params['scontent']."') ";
        }
        //排序字段  2、根据排序将goods_id的顺序重排
        $isOrderByPrice = false;
        $priceOrderType = '';
        $orderby = '';
        if(isset($params['order_list']) && !empty($params['order_list'])){
            foreach ($params['order_list'] as $ord_k => $ord_v) {
                if($ord_v['order_by']=='buy_count' || $ord_v['order_by']=='price'){
                    $orderby .= $ord_v['order_by'].' '.$ord_v['order_type'].', ';
                    if($ord_v['order_by']=='price'){
                        $isOrderByPrice = true;
                        $priceOrderType = $ord_v['order_type'];
                    }
                }else{
                    //todo 根据区域搜索
                }
            }
        }
        $orderby .= ' goods_order_down desc'; //默认根据权值排序

        //页码  3、根据筛选的ID及排序按分页查询数据
        $page_no = intval($params['page_no']) > 0 ? intval($params['page_no']) : 1;
        $limit   = (intval($params['page_size']) > 10 || intval($params['page_size']) <= 0) ? 10 : intval($params['page_size']);
        //查询结果
        if(empty($account_id)){
            $sql = "SELECT goods_id,name,price,mktprice,image_default_id,buy_count,preparesell FROM sdb_b2c_goods g WHERE ".$where." order by ".$orderby." limit ".($page_no-1)*$limit.",".$limit;
            $data = app::get('b2c')->model('goods')->db->select($sql);
        }else{
            // $sql = "select g.goods_id,g.name,s.price,g.image_default_id,g.buy_count,g.preparesell from sdb_b2c_goods as g left join sdb_b2c_goods_store as s on g.goods_id=s.goods_id where ".$where." and s.store_grade = ".$store_grade." order by ".$orderby." limit ".($page_no-1)*$limit.",".$limit;
            if($isOrderByPrice){
                $goodsSql = "select distinct s.goods_id from sdb_b2c_goods_store as s left join sdb_b2c_goods as g on g.goods_id=s.goods_id where ".$where." and s.store_grade = ".$store_grade." order by goods_order_down desc ";
                $goodsIds = app::get('b2c')->model('goods')->db->select($goodsSql);
                $goodsPrice = array();
                $list2dump = kernel::single("b2c_goods_list2dump");
                foreach ($goodsIds as $gk => $gv) {
                    $aGoods_list = app::get('b2c')->model('goods')->getList("*",array('goods_id'=>$gv['goods_id']));
                    $aGoods = $list2dump->get_goods($aGoods_list[0],$this->site_member_lv_id);
                    $goodsPrice[$gv['goods_id']] = $aGoods['current_price'];
                }
                if(strtoupper($priceOrderType)=='ASC'){
                    asort($goodsPrice);
                }else{
                    arsort($goodsPrice);
                }
                $start = ($page_no-1)*$limit;
                if($start>count($goodsPrice)){
                    $msg = $page_no>1?'没有更多了':'未找到任何商品';
                    return $this->apiData(false,null,400,app::get('b2c')->_($msg));
                }
                $data = array_slice($goodsPrice, $start,$limit,true);
                $rdata = app::get('b2c')->model('goods')->getList('goods_id,name,price,mktprice,image_default_id,buy_count,preparesell',array('goods_id|in'=>array_keys($data)));
                foreach ($rdata as $dk => $dv) {
                    $dv['mktprice'] = $dv['price'];
                    $dv['price'] = $data[$dv['goods_id']];
                    $data[$dv['goods_id']] = $dv;
                }
            }else{
                $sql = "select distinct s.goods_id,g.name,s.price,g.image_default_id,g.buy_count,g.preparesell from sdb_b2c_goods_store as s left join sdb_b2c_goods as g on g.goods_id=s.goods_id where ".$where." and s.store_grade = ".$store_grade." order by ".$orderby." limit ".($page_no-1)*$limit.",".$limit;
                $data = app::get('b2c')->model('goods')->db->select($sql);
            }
        }
        if(!$data){
            return $this->apiData(false,null,400,app::get('b2c')->_('未找到任何商品'));
        }
        $objGoods = app::get('b2c')->model('goods');
        $objPoint = app::get('business')->model('comment_goods_point');
        foreach ($data as $d_k => &$d_v) {
            $d_v['thumbnail_pic'] = kernel::single('base_storager')->image_path($d_v['image_default_id'],'s');
            //商品评分和星级
            $aGoods_list = $objGoods->getList('avg_point,comments_count',array('goods_id'=>$d_v['goods_id']));
            $rating = array('rating_num'=>$aGoods_list[0]['comments_count'],'rating_point'=>$aGoods_list[0]['avg_point'],'rating'=>round($aGoods_list[0]['avg_point'])); // 商品评分
            $d_v['rating'] = $rating;

            if(!$isOrderByPrice){
                //上级给定的价格
                $myprice = app::get('b2c')->model('goods_store')->getList("price",array('goods_id'=>$d_v['goods_id'],'store_grade'=>$store_grade));
                $d_v['price'] = $myprice[0]['price']>0?$myprice[0]['price']:$d_v['price'];
                //给下级定的价格
                $subprice = app::get('b2c')->model('goods_store')->getList("pirce",array('goods_id'=>$d_v['goods_id'],'store_grade'=>$sub_store_grade));
                //预计利润
                if($subprice[0]['price']>0){
                    $d_v['profit'] = $subprice[0]['price']-$d_v['price'];
                }else{
                    $limit = app::get('b2c')->model('goods_price_grade_limit')->getData($d_v['goods_id'],null,$sub_store_grade);
                    $d_v['profit'] = $limit[0]['limit_price']-$d_v['price'];
                }
                if($d_v['profit']<0){
                    $d_v['profit'] = 0;
                }
            }
            // $list2dump = kernel::single("b2c_goods_list2dump");
            // $aGoods = $list2dump->get_goods($d_v);
            // $d_v['price'] = number_format($aGoods['current_price'],2,".","");
            // $d_v['mktprice'] = number_format($aGoods['mktprice'],2,".","");

            //是否团购商品
            // $act_sql = "select p.* from sdb_groupbuy_groupprice p,sdb_groupbuy_activity a where a.gids like '%,".$d_v['goods_id'].",%' and a.start_time<=unix_timestamp(now()) and a.end_time>=unix_timestamp(now())";
            // $activity = kernel::database()->select($act_sql);
            // if(!empty($activity)){
            //     $d_v['is_activity'] = true;
            //     $actlist = array();
            //     foreach ($activity as $key => $act) {
            //         if($store_grade && ($store_grade==$act['grade_id'])){
            //             $d_v['activity_price'] = $act['group_price'];
            //             $d_v['activity_price_percent'] = $act['activity_price_percent'];
            //         }else{
            //             $actlist[$act['grade_id']] = $act['group_price'];
            //         }
            //     }
            //     $d_v['activity_price'] = 1;
            // }

            //是否预售商品
            if($d_v['preparesell']){
                $pre_sql = "SELECT * FROM sdb_preparesell_preparesell_goods where status='true' and prepare_id='".$d_v['preparesell']."' and begin_time<unix_timestamp(now()) and end_time>unix_timestamp(now());";
                $pre = kernel::database()->select($pre_sql);
                if(!empty($pre)){
                    $d_v['promotion_type'] = "Pre-sale";
                    if($store_grade){
                        $pre_price_sql = "SELECT preparesell_price FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id']." and grade_id=".$store_grade;
                    }else{
                        $pre_price_sql = "SELECT max(preparesell_price) preparesell_price FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id'];
                    }
                    $preparesell_price = kernel::database()->select($pre_price_sql);
                    $d_v['promotion_price'] = $preparesell_price[0]['preparesell_price'];
                    $d_v['promotion_desc'] = '';
                }
            }
            unset($d_v['preparesell']);
        }
        return $this->apiData(true,kernel::single('openapi_utils_datahelper')->array_merge_fb($data),200);
    }

    /**
     * 查询货品列表
     * @param
     * @return
     **/
    /*public function getList($params,&$code,&$sub_msg)
    {
        $params = array_filter($params);
        $account_id = $this->checklogin($params['login_token']);
        $store_grade = 0;
        $sub_store_grade = 0;
        if($account_id){
            $store = app::get("business")->model('storemanger')->getRow("store_grade",array('account_id'=>$account_id));
            $store_grade = $store['store_grade'];
            $substore = app::get('business')->model('storegrade')->getRow('grade_id',array('parent_id'=>$store_grade));
            $sub_store_grade = $substore['grade_id'];
        }
        //筛选条件
        $where = "1=1 ";
        if(isset($params['cat_id']) && !empty($params['cat_id'])){
            $cats = app::get('b2c')->model('goods_cat')->getList("cat_id",array('cat_path|has'=>','.$params['cat_id'].','));
            $new_cats = array();
            foreach ($cats as $key => $value) {
                $new_cats[] = $value['cat_id'];
            }
            $new_cats[] = $params['cat_id'];
            $where .= "and g.cat_id in ('".implode("','", $new_cats)."') ";
        }
        if(isset($params['filter_list']) && !empty($params['filter_list'])){
            foreach ($params['filter_list'] as $f_k => $f_v) {
                if($f_v['name']=='spec' || $f_v['name']=='rating'){
                    continue;//todo
                }
                if($f_v['type']=='between'){
                    $f_v['content'] = explode(',', $f_v['content']);
                    $where .= "and (g.".$f_v['name']." between ".$f_v['content'][0]." and ".$f_v['content'][1].") ";
                }elseif ($f_v['type']=='in') {
                    $f_v['content'] = explode(',', $f_v['content']);
                    $where .= " and g.".$f_v['name']." in ('".implode("','", $f_v['content'])."') ";
                }
            }
        }

        //排序字段
        $orderby = '';
        if(isset($params['order_list']) && !empty($params['order_list'])){
            $ord_v = $params['order_list'];
            if($ord_v['order_by']=='buy_count' || $ord_v['order_by']=='price'){
                $orderby .= 'g.'.$ord_v['order_by'].' '.$ord_v['order_type'].', ';
            }else{
                //todo 根据区域搜索
            }
        }

        $orderby .= '1';

        //搜索条件
        if(isset($params['scontent']) && !empty($params['scontent'])){
            $where .= " and (g.name like '%".$params['scontent']."%' or g.bn like '%".$params['scontent']."' or p.bn like '%".$params['scontent']."') ";
        }
        //页码
        $page_no = intval($params['page_no']) > 0 ? intval($params['page_no']) : 1;
        $limit   = (intval($params['page_size']) > 20 || intval($params['page_size']) <= 0) ? 10 : intval($params['page_size']);
        //查询结果
        $sql = "SELECT g.goods_id,p.product_id,g.name,g.price,g.mktprice,g.image_default_id,g.buy_count,g.preparesell FROM sdb_b2c_goods g RIGHT JOIN sdb_b2c_products p ON g.goods_id=p.goods_id WHERE ".$where." order by ".$orderby." limit ".($page_no-1)*$limit.",".$limit;
        $data = app::get('b2c')->model('goods')->db->select($sql);
        if(!$data){
            $errmsg = ($page_no>1)?'没有更多了':'未找到任何商品';
            return $this->apiData(false,null,400,app::get('b2c')->_($errmsg));
        }
        $objGoods = app::get('b2c')->model('goods');
        $objPoint = app::get('business')->model('comment_goods_point');
        foreach ($data as $d_k => &$d_v) {
            if(!$d_v['image_default_id']){
                $d_v['thumbnail_pic'] = base_storager::image_path( $imageDefault['S']['default_image'],'m' );
            }else{
                $d_v['thumbnail_pic'] = base_storager::image_path($d_v['image_default_id'],'m' );
            }
            //商品评分和星级
            $aGoods_list = $objGoods->getList('avg_point,comments_count',array('goods_id'=>$d_v['goods_id']));
            $rating = array('rating_num'=>$aGoods_list[0]['comments_count'],'rating_point'=>$aGoods_list[0]['avg_point'],'rating'=>round($aGoods_list[0]['avg_point'])); // 商品评分
            $d_v['rating'] = $rating;

            $list2dump = kernel::single("b2c_goods_list2dump");
            $aGoods = $list2dump->get_goods($d_v);

            //是否团购商品
            // $act_sql = "select p.* from sdb_groupbuy_groupprice p,sdb_groupbuy_activity a where a.gids like '%,".$d_v['goods_id'].",%' and a.start_time<=unix_timestamp(now()) and a.end_time>=unix_timestamp(now())";
            // $activity = kernel::database()->select($act_sql);
            // if(!empty($activity)){
            //     $d_v['is_activity'] = true;
            //     $actlist = array();
            //     foreach ($activity as $key => $act) {
            //         if($store_grade && ($store_grade==$act['grade_id'])){
            //             $d_v['activity_price'] = $act['group_price'];
            //             $d_v['activity_price_percent'] = $act['activity_price_percent'];
            //         }else{
            //             $actlist[$act['grade_id']] = $act['group_price'];
            //         }
            //     }
            //     $d_v['activity_price'] = 1;
            // }

            //是否预售商品
            if($d_v['preparesell']){
                $pre_sql = "SELECT * FROM sdb_preparesell_preparesell_goods where status='true' and product_id='".$d_v['product_id']."' and begin_time<unix_timestamp(now()) and end_time>unix_timestamp(now());";
                $pre = kernel::database()->select($pre_sql);
                if(!empty($pre)){
                    $d_v['promotion_type'] = "prepare";
                    if($store_grade){
                        $pre_price_sql = "SELECT preparesell_price FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id']." and grade_id=".$store_grade;
                    }else{
                        $pre_price_sql = "SELECT max(preparesell_price) preparesell_price FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id'];
                    }
                    $preparesell_price = kernel::database()->select($pre_price_sql);
                    $d_v['promotion_price'] = $preparesell_price[0]['preparesell_price'];
                    $d_v['promotion_desc'] = '';
                }
            }
            unset($d_v['preparesell']);

            //经销商折扣 todo

            //可获得利润
            if($store_grade){
                //上级给定的价格
                $myprice = app::get('b2c')->model('goods_store')->getList("price",array('goods_id'=>$d_v['goods_id'],'store_grade'=>$store_grade));
                $d_v['price'] = $myprice[0]['price']>0?$myprice[0]['price']:$d_v['price'];
                //给下级定的价格
                $subprice = app::get('b2c')->model('goods_store')->getList("pirce",array('goods_id'=>$d_v['goods_id'],'store_grade'=>$sub_store_grade));
                //预计利润
                if($subprice[0]['price']>0){
                    $d_v['profit'] = $subprice[0]['price']-$d_v['price'];
                }else{
                    $limit = app::get('b2c')->model('goods_price_grade_limit')->getData($d_v['goods_id'],null,$sub_store_grade);
                    $d_v['profit'] = $limit[0]['limit_price']-$d_v['price'];
                }
                if($d_v['profit']<0){
                    $d_v['profit'] = 0;
                }
                //活动重新计算利润
                if(!empty($d_v['promotion_price']) && !empty($sub_store_grade)){
                    $sub_pre_price_sql = "SELECT preparesell_price FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id']." and grade_id=".$sub_store_grade;
                    $sub_preparesell_price = kernel::database()->select($sub_pre_price_sql);
                    $d_v['profit'] = $sub_preparesell_price[0]['preparesell_price'] - $d_v['promotion_price'];
                }
            }
            $d_v['price'] = number_format($aGoods['current_price'],2,".","");
            $d_v['mktprice'] = number_format($aGoods['mktprice'],2,".","");
        }
        return $this->apiData(true,$data,200);
    }
*/

    public function detail($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        $store_grade = null;
        $sub_store_grade = null;
        $store_id = null;
        if($member_id){
            $store = app::get("business")->model('storemanger')->getRow("store_grade,store_id",array('account_id'=>$member_id));
            $store_grade = $store['store_grade'];
            $store_id = $store['store_id'];
            $substore = app::get('business')->model('storegrade')->getRow('grade_id',array('parent_id'=>$store_grade));
            $sub_store_grade = $substore['grade_id'];
        }
        $member = $this->get_current_member();
        $site_member_lv_id = $member['member_lv'];
        $gid = $params['goods_id'];
        $objProduct = app::get('b2c')->model('products');
        $objGoods = app::get('b2c')->model('goods');
        //商品信息
        $goods_list = $objGoods->getList("*",array('goods_id'=>$params['goods_id']));
        if(empty($goods_list)){
            return $this->apiData(false,null,400,app::get('b2c')->_('该商品不存在'));
        }
        $list2dump = kernel::single("b2c_goods_list2dump");
        $aGoods = $list2dump->get_goods($goods_list[0],$site_member_lv_id);
        // print_r($aGoods);
        //商品图片地址
        foreach ($aGoods['images'] as $img_k => &$img_v) {
            $img_v['image_url'] = base_storager::image_path($img_v['image_id'],'m');
        }
        //获取货品价格和最小购买量
        foreach($aGoods['product'] as $gpk => &$gpv){
            $currentPriceArea[]=$gpv['price']['price']['current_price'];//销售价区域
            $priceArea[]=$gpv['price']['price']['price'];//销售价区域
            if( $gpv['price']['mktprice']['price'] == '' || $gpv['price']['mktprice']['price'] == null ){
                $mktpriceArea[]= $objProduct->getRealMkt($gpv['price']['mktprice']['price']);
            }else{
                $mktpriceArea[]=$gpv['price']['mktprice']['price'];//市场价区域
            }
            $buyLimit[] = $gpv['min_buy'];
            if($store_grade){
                //给下级定的价格
                $subprice = app::get('b2c')->model('goods_store')->getList("pirce",array('goods_id'=>$gpv['goods_id'],'product_id'=>$gpv['product_id'],'store_grade'=>$sub_store_grade));
                //预计利润
                if($subprice[0]['price']>0){
                    $gpv['profit'] = $subprice[0]['price']-$gpv['price']['price']['current_price'];
                }else{
                    $limit = app::get('b2c')->model('goods_price_grade_limit')->getData($gpv['goods_id'],$gpv['product_id'],$sub_store_grade);
                    $gpv['profit'] = $limit[0]['limit_price']-$gpv['price']['price']['current_price'];
                }
                if($gpv['profit']<0){
                    $gpv['profit'] = 0;
                }
                $profitArea[] = $gpv['profit'];
            }
            $gpv['store'] = intval($gpv['store'])-intval($gpv['freez']);

            //规格id数组转字符串
            $gpv['spec_desc']['spec_value_id'] = implode(",", $gpv['spec_desc']['spec_value_id']);

            //获取经销商某商品的折扣
            $discountInfo = kernel::single('b2c_goods_store')->getDiscountList($gpv['goods_id'],$gpv['product_id'],$store_id);
            $gpv['discountInfo']=!empty($discountInfo)?array('start_time'=>$discountInfo[0]['start_time'],'end_time'=>$discountInfo[0]['end_time'],'active_discount'=>$discountInfo[0]['active_discount'],'discount'=>$discountInfo[0]['discount']):null;
            if($aGoods['act_type']=='normal'){//普通商品都参与折扣
                $gpv['discountInfo']['active_discount'] = 'true';
            } 
            //判断是否参与活动
            //1、是否预售商品
            if($goods_list[0]['preparesell']>0){
                $pre_sql = "SELECT * FROM sdb_preparesell_preparesell_goods where status='true' and prepare_id='".$goods_list[0]['preparesell']."' and begin_time<unix_timestamp(now()) and end_time>unix_timestamp(now());";
                $pre = kernel::database()->select($pre_sql);
                if(!empty($pre)){
                    //预售商品库存无限制
                    $gpv['store'] = 999999;
                    $gpv['promotion_type'] = "Pre-sale";
                    if($store_grade){
                        $pre_price_sql = "SELECT preparesell_price,deposit_percent,deposit FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id']." and grade_id=".$store_grade;
                    }else{
                        $pre_price_sql = "SELECT preparesell_price,deposit_percent,deposit FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id']." and preparesell_price=(SELECT max(preparesell_price) FROM sdb_preparesell_preparesell_price where prepare_id=".$pre[0]['prepare_id']." and product_id=".$pre[0]['product_id'].")";
                    }
                    $preparesell_price = kernel::database()->select($pre_price_sql);
                    $gpv['promotion_price'] = $preparesell_price[0]['preparesell_price'];
                    $gpv['promotion_detail'] = array(
                            'description'=>$pre[0]['description'],
                            'begin_time'=>$pre[0]['begin_time'],
                            'end_time'=>$pre[0]['end_time'],
                            'end_time_first'=>$pre[0]['end_time_first'],
                            'end_time_final'=>$pre[0]['end_time_final'],
                            'deposit_percent'=>$preparesell_price[0]['deposit_percent'],
                            'deposit'=>$preparesell_price[0]['deposit'],
                        );
                }
            }
            if($gpv['store']<1){
                $gpv['replenishment'] = $this->get_replenishment($gpv['product_id']);
            }
        }

        //判断是否参与活动
        $result['act_type'] = $aGoods['act_type'];
        $result['act_id'] = $aGoods['act_id'];
        if($aGoods['act_type'] == 'timedbuy'&& $aGoods['act_id']){
            $mdl_activity = app::get('timedbuy')->model('activity');
            $result['isTimedbuy'] = true;
            $result['act_info'] = $mdl_activity->getRow('*',array('act_id'=>$aGoods['act_id']));
            // $result['goodshtml']['store'] = kernel::single('timedbuy_goods_detail_store')->show($gid,$aGoods);
        }else if($aGoods['act_type'] == 'group' && $aGoods['act_id']){
            $mdl_activity = app::get('groupbuy')->model('activity');
            $result['isGroupbuy'] = true;
            $result['act_info'] = $mdl_activity->getRow('*',array('act_id'=>$aGoods['act_id']));
            // $result['goodshtml']['store'] = kernel::single('groupbuy_goods_detail_store')->show($gid,$aGoods);
        }else if($aGoods['act_type'] == 'spike' && $aGoods['act_id']){
            $mdl_activity = app::get('spike')->model('activity');
            $result['isSpike'] = true;
            $result['act_info'] = $mdl_activity->getRow('*',array('act_id'=>$aGoods['act_id']));
            // $result['goodshtml']['store'] = kernel::single('spike_goods_detail_store')->show($gid,$aGoods);
        }else if($aGoods['act_type'] == 'preparesell' && $aGoods['act_id']){
            $result['isPreparesell'] = true;
            // $result['goodshtml']['store'] = kernel::single('b2c_goods_detail_store')->show($gid,$aGoods);
        }else{
            // $result['goodshtml']['store'] = kernel::single('b2c_goods_detail_store')->show($gid,$aGoods);
        }

        $aGoods['min_buy'] = min($buyLimit);
        if (count($currentPriceArea)>1){
           $aGoods['current_price'] = min($currentPriceArea);
        }
        //价格区间
        if (count($priceArea)>1){
            $minprice = min($priceArea);
            $maxprice = max($priceArea);
            if ($minprice<>$maxprice){
                $result['minprice'] = $minprice;
                $result['maxprice'] = $maxprice;
            }
        }
        $result['price'] = min($priceArea);
        //市场价区间
        if (app::get('b2c')->getConf('site.show_mark_price')=="true" && count($mktpriceArea)>1){
            $mktminprice = min($mktpriceArea);
            $mktmaxprice = max($mktpriceArea);
            if ($mktminprice<>$mktmaxprice){
                $result['minmktprice'] = $mktminprice;
                $result['maxmktprice'] = $mktmaxprice;
            }
        }
        $result['mktprice'] = min($mktpriceArea);
        //可获得利润
        if(count($profitArea)>1){
            $result['minprofit'] = min($profitArea);
            $result['maxprofit'] = max($profitArea);
        }
        $result['profit'] = max($profitArea);

        //组合商品
        if($aGoods['combined'] == 'true'){
            $sql = 'select i.product_id,i.quantity,p.name,p.spec_info,p.goods_id,g.image_default_id from sdb_b2c_combine_item i,sdb_b2c_products p,sdb_b2c_goods g where i.goods_id='.$aGoods['goods_id'].' and i.product_id=p.product_id and p.goods_id=g.goods_id';
            $items = $objGoods->db->select($sql);
            foreach($items as $k=>$v){
                if(!$v['image_default_id']){
                    $items[$k]['image'] = base_storager::image_path( $imageDefault['S']['default_image'],'s' );
                }else{
                    $items[$k]['image'] = base_storager::image_path($v['image_default_id'],'s');
                }
            }
            $result['combine_goods'] = $items;
        }
        //获取商品属性
        $props = array();
        foreach ($aGoods['type']['props'] as $pk => $pv) {
            if(empty($pv['show']) || $pv['show']!='on'){
                continue;
            }
            if(empty($aGoods['props']['p_'.$pv['goods_p']]['value'])){
                continue;
            }
            $tp = array();
            $tp['props_id'] = $pv['props_id'];
            $tp['name'] = $pv['name'];
            $tp['alias'] = $pv['alias'];
            $tp['ordernum'] = $pv['ordernum'];
            $tp['content'] = $aGoods['props']['p_'.$pv['goods_p']]['value'];
            $props[] = $tp;
        }

        //商品规格图片格式处理
        if($aGoods['spec']){
            foreach ($aGoods['spec'] as $key => &$spec) {
                foreach ($spec['option'] as $key => &$option) {
                    $tmp_spec_image = array();
                    $tmp_spec_image = explode(",", $option['spec_goods_images']);
                    $option['spec_goods_images'] = array();
                    foreach ($tmp_spec_image as $key => $value) {
                        $option['spec_goods_images'][] = array('image_id'=>$value);
                    }
                }
            }
        }

        //商品评分和星级
        $objGoods = app::get('b2c')->model('goods');
        $objPoint = app::get('business')->model('comment_goods_point');
        $aGoods_list = $objGoods->getList('avg_point,comments_count',array('goods_id'=>$params['goods_id']));
        $rating = array('rating_num'=>$aGoods_list[0]['comments_count'],'rating_point'=>$aGoods_list[0]['avg_point'],'rating'=>round($aGoods_list[0]['avg_point'])); // 商品评分
        $result['rating'] = $rating;
        //是否已加入心愿单
        $fav = app::get('b2c')->model('member_goods')->getRow('*',array('goods_id'=>$params['goods_id'], 'member_id'=>$member['member_id']));
        $result['fav'] = empty($fav) ? false : true;
        //反序列化商品配件信息
        if(!is_array($aGoods['adjunct'])){
            $aGoods['adjunct'] = unserialize($aGoods['adjunct']);
        }

        //去掉数组下标和多余数据
        unset($aGoods['props']);//商品属性
        $result['goods_id'] = $aGoods['goods_id'];
        $result['bn'] = $aGoods['bn'];
        $result['name'] = $aGoods['name'];
        $result['cat_id'] = $aGoods['category']['cat_id'];
        $result['brand'] = $aGoods['brand'];
        $result['unit'] = $aGoods['unit'];
        $result['brief'] = $aGoods['brief'];
        $result['image_default_id'] = $aGoods['image_default_id'];
        $result['score_setting'] = $aGoods['score_setting'];
        $result['nostore_sell'] = $aGoods['nostore_sell'];
        $result['adjunct'] = $aGoods['adjunct'];
        $result['weight'] = $aGoods['weight'];
        $result['goods_state'] = $aGoods['goods_state'];
        $result['fav_count'] = $aGoods['fav_count'];
        $result['store_id'] = $aGoods['store_id'];
        $result['buy_m_count'] = $aGoods['buy_m_count'];
        $result['freight_bear'] = $aGoods['freight_bear'];
        $result['store_freeze'] = $aGoods['store_freeze'];
        $result['store'] = $aGoods['store']-$aGoods['store_freeze'];
        $result['marketable'] = $aGoods['marketable'];
        $result['current_price'] = $aGoods['current_price'];
        $result['description'] = "/index.php/product-goodsDescriptionApi-".$aGoods['goods_id'].".html";
        $result['min_buy'] = $aGoods['min_buy'];

        $result['type'] = array('type_id'=>$aGoods['type']['type_id'],'name'=>$aGoods['type']['name']);
        $result['images'] = array_values($aGoods['images']);
        $result['product'] = array_values($aGoods['product']);
        $result['spec'] = array_values($aGoods['spec']);
        $result['props'] = $props;
        $result['link_url'] = app::get('site')->router()->gen_url(array('app'=>'b2c','ctl'=>'site_product','args'=>array($aGoods['goods_id']),'full'=>true));
        $result = openapi_utils_datahelper::array_merge_fb($result);
        return $this->apiData(true,$result,200);
    }

    /**
     * 获取关联经销商商品信息
     * @param
     * @return
     * @author hmg
     **/
    private function get_replenishment($product_id)
    {
        $ass_store = kernel::single("b2c_goods_list2dump")->get_replenishment($product_id);
        foreach ($ass_store as $store_id => $storeinfo) {
            $addr = explode(':',$storeinfo['addr']['area']);
            $storeinfo['addr'] = str_replace('/', '-', $addr[1]).' '.$storeinfo['addr']['addr'];
            $ass_store[] = $storeinfo;
            unset($ass_store[$store_id]);
        }
        return $ass_store;
    }

    public function getCats($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        $parent_id = empty($params['parent_id'])?0:$params['parent_id'];
        $catsList = app::get('b2c')->model('goods_cat')->getList("cat_id,parent_id,is_leaf,type_id,cat_name,disabled,p_order,goods_count,tabs,child_count,cat_logo",array('parent_id'=>$parent_id));
        if(empty($catsList)){
            return $this->apiData(false,null,400,app::get('b2c')->_('没有子分类了'));
        }
        foreach ($catsList as $cat_k => &$cat_v) {
            if(!empty($cat_v['cat_logo'])){
                $img = app::get('image')->model('image')->getList("url",array('image_id'=>$cat_v['cat_logo']));
                $cat_v['cat_logo'] = $img[0]['url'];
            }
            $has_next = app::get('b2c')->model('goods_cat')->getList("*",array('parent_id'=>$cat_v['cat_id']));
            if(!empty($has_next)){
                $cat_v['has_next'] = true;
            }else{
                $cat_v['has_next'] = false;
                $cat_v['goods_count'] = app::get('b2c')->model('goods')->count(array('cat_id'=>$cat_v['cat_id']));
            }
        }
        return $this->apiData(true,$catsList,200);
    }

    public function leftFilter($params,&$code,&$sub_msg)
    {
        $member_id = $this->checklogin($params['login_token']);
        $ogoods = app::get('b2c')->model('goods');
        //该分类中所有商品的规格和品牌
        $glist = $ogoods->getList("spec_desc,brand_id,price,mktprice",array('cat_id'=>$params['cat_id']));

        //过滤商品中的规格、品牌
        $tmp_spec_desc = array();
        $tmp_brand = array();
        $priceArea = array();
        foreach ($glist as $gk => $gv) {
            //查找分类商品中具有的规格值
            $spec_desc = $gv['spec_desc'];
            if(!empty($spec_desc)){
                foreach ($spec_desc as $sk => $sv) {
                    foreach ($sv as $ssk => $ssv) {
                        $tmp_spec_desc[$sk][] = array('spec_value_id'=>$ssv['spec_value_id'],'spec_value'=>$ssv['spec_value'],'count'=>$ogoods->count(array('spec_desc|has'=>$ssv['spec_value'])));
                    }
                }
            }
            //过滤此分类商品具有的品牌分类
            if(!in_array($gv['brand_id'], $tmp_brand)){
                $tmp_brand[] = $gv['brand_id'];
            }
            //取得价格区间
            if($gv['price']){
                $priceArea[] = $gv['price'];
            }
            if($gv['mktprice']){
                $priceArea[] = $gv['mktprice'];
            }
        }

        //规格去重
        foreach ($tmp_spec_desc as $key => &$value) {
            $value = openapi_utils_datahelper::array_unique_fb($value,"spec_value_id");
        }
        //根据商品中过滤出的规格查询信息
        $spec_desc = app::get('b2c')->model('specification')->getList("spec_id,spec_name",array('spec_id|in'=>array_keys($tmp_spec_desc)));
        foreach ($spec_desc as $sk => &$sv) {
            foreach ($tmp_spec_desc[$sv['spec_id']] as $key => $spec) {
                $sv['count'] += $spec['count'];
            }
            $sv['items'] = $tmp_spec_desc[$sv['spec_id']];
            $result[] = $sv;
        }
        //根据商品的品牌查询名称
        $oBrand = app::get('b2c')->model('brand');
        $gtype['brand'] = $oBrand->getList('brand_id,brand_name',array('brand_id|in'=>$tmp_brand),0,-1);
        $brand['count'] = 0;
        foreach ($gtype['brand'] as $bk => &$bv) {
            $bv['spec_value_id'] = $bv['brand_id'];
            $bv['spec_value'] = $bv['brand_name'];
            $brand['count'] += $bv['count'] = $ogoods->count(array('cat_id'=>$params['cat_id'],'brand_id'=>$bv['brand_id']));
            unset($bv['brand_id']);
            unset($bv['brand_name']);
        }
        $brand['spec_id'] = 'brand';
        $brand['spec_name'] = 'brand';
        $brand['items'] = $gtype['brand'];
        $result[] = $brand;
        //价格区间
        $priceAreaRes['spec_id'] = 'priceArea';
        $priceAreaRes['spec_name'] = 'priceArea';
        $priceAreaRes['count'] = 0;
        $priceAreaRes['items'] = array('minprice'=>min($priceArea),'maxprice'=>max($priceArea));
        $result[] = $priceAreaRes;
        return $this->apiData(true,$result,200);
    }

    public function getListByIds($params,&$code,&$sub_msg){
        $member_id = $this->checklogin($params['login_token']);
        $store_grade = 0;
        $sub_store_grade = 0;
        if($member_id){
            $store = app::get("business")->model('storemanger')->getRow("store_grade",array('account_id'=>$member_id));
            $store_grade = $store['store_grade'];
            $substore = app::get('business')->model('storegrade')->getRow('grade_id',array('parent_id'=>$store_grade));
            $sub_store_grade = $substore['grade_id'];
        }
        if(!empty($params['ids'])){
            $ids = explode(',', $params['ids']);
            $list = array();
            foreach ($ids as $key => $id) {
                $objProduct = app::get('b2c')->model('products');
                $objGoods = app::get('b2c')->model('goods');
                //商品信息
                $goods_list = $objGoods->getList("*",array('goods_id'=>$id));
                if(empty($goods_list)){
                    continue;
                }
                $list2dump = kernel::single("b2c_goods_list2dump");
                $aGoods = $list2dump->get_goods($goods_list[0],$site_member_lv_id);
                // print_r($aGoods);
                //商品图片地址
                foreach ($aGoods['images'] as $img_k => &$img_v) {
                    $img = openapi_utils_image::getimgbyid($img_v['image_id']);
                    $img_v['image_url'] = empty($img['l_url'])?$img['url']:$img['l_url'];
                }
                //获取货品价格和最小购买量
                $profitArea = array();
                foreach($aGoods['product'] as $gpk => &$gpv){
                    $currentPriceArea[]=$gpv['price']['price']['current_price'];//销售价区域
                    $priceArea[]=$gpv['price']['price']['price'];//销售价区域
                    if( $gpv['price']['mktprice']['price'] == '' || $gpv['price']['mktprice']['price'] == null ){
                        $mktpriceArea[]= $objProduct->getRealMkt($gpv['price']['mktprice']['price']);
                    }else{
                        $mktpriceArea[]=$gpv['price']['mktprice']['price'];//市场价区域
                    }
                    $buyLimit[] = $gpv['min_buy'];
                    if($store_grade){
                        //给下级定的价格
                        $subprice = app::get('b2c')->model('goods_store')->getList("pirce",array('goods_id'=>$gpv['goods_id'],'product_id'=>$gpv['product_id'],'store_grade'=>$sub_store_grade));
                        //预计利润
                        if($subprice[0]['price']>0){
                            $gpv['profit'] = $subprice[0]['price']-$gpv['price']['price']['current_price'];
                        }else{
                            $limit = app::get('b2c')->model('goods_price_grade_limit')->getData($gpv['goods_id'],$gpv['product_id'],$sub_store_grade);
                            $gpv['profit'] = $limit[0]['limit_price']-$gpv['price']['price']['current_price'];
                        }
                        if($gpv['profit']<0){
                            $gpv['profit'] = 0;
                        }
                        $profitArea[] = $gpv['profit'];
                    }
                }
                $aGoods['min_buy'] = min($buyLimit);
                if (count($currentPriceArea)>1){
                   $aGoods['current_price'] = min($currentPriceArea);
                }
                //价格区间
                if (count($priceArea)>1){
                    $minprice = min($priceArea);
                    $maxprice = max($priceArea);
                    if ($minprice<>$maxprice){
                        $result['minprice'] = $minprice;
                        $result['maxprice'] = $maxprice;
                    }
                }
                $result['price'] = min($priceArea);
                //市场价区间
                if (app::get('b2c')->getConf('site.show_mark_price')=="true" && count($mktpriceArea)>1){
                    $mktminprice = min($mktpriceArea);
                    $mktmaxprice = max($mktpriceArea);
                    if ($mktminprice<>$mktmaxprice){
                        $result['minmktprice'] = $mktminprice;
                        $result['maxmktprice'] = $mktmaxprice;
                    }
                }
                $result['mktprice'] = min($mktpriceArea);
                //可获得利润
                if(count($profitArea)>1){
                    $result['minprofit'] = min($profitArea);
                    $result['maxprofit'] = max($profitArea);
                }
                $result['profit'] = max($profitArea);


                //商品评分和星级
                $objGoods = app::get('b2c')->model('goods');
                $objPoint = app::get('business')->model('comment_goods_point');
                $aGoods_list = $objGoods->getList('avg_point,comments_count',array('goods_id'=>$d_v['goods_id']));
                $rating = array('rating_num'=>$aGoods_list[0]['comments_count'],'rating_point'=>$aGoods_list[0]['avg_point'],'rating'=>round($aGoods_list[0]['avg_point'])); // 商品评分
                $result['rating'] = $rating;
                //是否已加入心愿单
                $fav = app::get('b2c')->model('member_goods')->getRow('*',array('goods_id'=>$aGoods['goods_id'], 'member_id'=>$member_id));
                $result['fav'] = empty($fav) ? false : true;
                $img = openapi_utils_image::getimgbyid($aGoods['image_default_id']);
                //去掉数组下标和多余数据
                unset($aGoods['props']);//商品属性
                $result['goods_id'] = $aGoods['goods_id'];
                $result['bn'] = $aGoods['bn'];
                $result['name'] = $aGoods['name'];
                $result['cat_id'] = $aGoods['category']['cat_id'];
                $result['brand'] = $aGoods['brand'];
                $result['image_default_url'] = empty($img['m_url'])?(empty($img['l_url'])?$img['url']:$img['l_url']):$img['m_url'];
                $result['score_setting'] = $aGoods['score_setting'];
                $result['nostore_sell'] = $aGoods['nostore_sell'];
                $result['weight'] = $aGoods['weight'];
                $result['goods_state'] = $aGoods['goods_state'];
                $result['fav_count'] = $aGoods['fav_count'];
                $result['store_id'] = $aGoods['store_id'];
                $result['buy_m_count'] = $aGoods['buy_m_count'];
                $result['freight_bear'] = $aGoods['freight_bear'];
                $result['store_freeze'] = $aGoods['store_freeze'];
                $result['store'] = $aGoods['store'];
                $result['marketable'] = $aGoods['marketable'];
                $result['current_price'] = $aGoods['current_price'];
                $result['min_buy'] = $aGoods['min_buy'];

                $result['images'] = array_values($aGoods['images']);

                $list[$key] = $result;
            }
            $list = openapi_utils_datahelper::array_merge_fb($list);
            return $this->apiData(true,$list,200);
        }
        return $this->apiData(false,null,400,app::get('b2c')->_('参数错误！'));
    }


}